const { readFileSync } = require('fs');
const http = require('http');
const server = http.createServer();
server.listen(3000, () =>
	console.log('服务器开启了，点击访问：http://127.0.0.1:3000')
);

server.on('request', (request, response) => {
    console.log(request.url, request.url === '/showToken.js')
	if (request.url === '/showToken.js') {
		getJs(response);
		return;
	}

	if (request.url === '/') {
		response.end(readFileSync('./serve.html', 'utf-8'));
		return;
	}

	console.log('接收到了请求');

	// 假设访问时间有一秒
	setTimeout(() => {
		response.writeHead(200, {
			//设置状态码和响应头
			'Content-Type': 'text/html;charset=utf-8',
		});
		response.end('你好，服务器已经搭建完成，不在转圈圈了');
		//响应结果（也叫响应体），最后必须设置end做出响应
	}, 1000);
});

function getJs(response) {
	response.writeHead(200, {
		//设置状态码和响应头
		'Content-Type': 'text/html;charset=utf-8',
		'Access-Control-Allow-Origin': '*',
		'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
		'Access-Control-Allow-Headers':
			'Content-Type, Authorization, X-Requested-With',
	});
	response.end(readFileSync('./showToken.js', 'utf-8'));
	return;
}


